package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject





/**
 *
 * @Title: WaterLiveHis
 * @Description:live800-- 对接获取当前用户编号网聊历史--外部接口
 * @author: cheih
 * @date 2021-11-24 10:28:00
 *
 */

public class WaterLiveHis implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(WaterLiveHis.class);

	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			
			
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());
			def userId = GetJV(inObject, "userId");//时间

			log.debug("解析信息-" +"	userId: " + userId);
			long startTime = System.currentTimeMillis();
			String reJson = null;
			long endTime = 0;

			long timestamp=new Date().getTime();
			String key="live800Key";
			String signature="";
			String signafter="";
			String doURL="";
			
			log.debug(userId);
			log.debug(timestamp);
			log.debug(key);
			try {
				signafter=URLEncoder.encode(userId+timestamp+key,"utf-8").toUpperCase();
				signature=getSHA256StrJava(signafter);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			log.debug(signafter);
			log.debug(signature);
			//doURL="https://onlinetest.82137777.com/mg/webapi/chatRecord?userId="+userId+"&timestamp="+timestamp+"&signature="+signature;
			doURL="https://online.82137777.com/mg/webapi/chatRecord?userId="+userId+"&timestamp="+timestamp+"&signature="+signature;
			log.debug(doURL);
			String getResult = Util.doHttpGet(doURL, "UTF-8", 100000, 0);
			//log.debug(getResult.toString());
			endTime = System.currentTimeMillis();
			outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + getResult.toString() + "}";
			
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
		}

		log.debug("短信数据接入处理完成返回结果:" + outData);

		return outData;
	}

		// 解析Json值
		public static String GetJV(JSONObject inJson, String getKey) {
			String Rev_Value = null;
			try {
				Rev_Value = inJson.getString(getKey);
			} catch (Exception e) {
				try {
					Rev_Value = String.valueOf(inJson.getInt(getKey));
				} catch (Exception e1) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
					} catch (Exception e2) {
						try {
							Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
						} catch (Exception e3) {
							Rev_Value = "";
						}
					}
				}
			} finally {
				if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
					Rev_Value = "";
				} else {
				}
			}
			log.debug("解析-k=" + getKey + " v=" + Rev_Value);
			return Rev_Value;
		}


		// 非空校验isNull
		public static boolean isNull(String value) {

			boolean reFlag = true;
			if (value == "" || value.length() <= 0) {
				reFlag = true;
			} else {
				reFlag = false;
			}
			log.debug(reFlag);
			return reFlag;
		}

		// 非空校验isNullMSG
		public static String isNullMSG(String key, String value) {

			String reResult = "";
			if (value == "" || value.length() <= 0) {
				reResult = key + "必填字段;";
			}
			return reResult;
		}
		
		public static String getSHA256StrJava(String str) {

        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
	        } catch (NoSuchAlgorithmException e) {
	            e.printStackTrace();
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }
	        return encodeStr;
	    }
	
	    private static String byte2Hex(byte[] bytes) {
	        StringBuffer stringBuffer = new StringBuffer();
	        String temp = null;
	        for (int i = 0; i < bytes.length; i++) {
	            temp = Integer.toHexString(bytes[i] & 0xFF);
	            if (temp.length() == 1) {
			//1得到一位的进行补0操作
			                stringBuffer.append("0");
			            }
			            stringBuffer.append(temp);
			        }
			        return stringBuffer.toString();
			}

	}
